package cn.kgc.listener;

import cn.kgc.constant.OrderConstant;
import cn.kgc.constant.OrderStatusEnum;
import cn.kgc.entity.OmsOrder;
import cn.kgc.service.OmsOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>添加描述信息</p>
 *
 * @author 卢传琪
 */
@Component
@Slf4j
public class MyRabbitListener {
    @Resource
    private OmsOrderService omsOrderService;

    /**
     * 监听订单超时消息
     * @param omsOrder 订单信息
     * @param channel 通道
     * @param message 消息
     */
    @RabbitListener(queues = OrderConstant.ORDER_RELEASE_QUEUE)
    @RabbitHandler
    public void receiveOrderReleaseMessage(OmsOrder omsOrder, Channel channel, Message message){
        long tag= message.getMessageProperties().getDeliveryTag();
        try {
            //订单编号
            String orderSn = omsOrder.getOrderSn();
            //根据订单编号，查询订单对应的最新的状态，如果状态是未付款，则关闭订单（订单超时，关闭订单）
            LambdaQueryWrapper<OmsOrder> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OmsOrder::getOrderSn,orderSn);
            omsOrder = omsOrderService.getOne(lambdaQueryWrapper);
            //订单状态是未付款
            if (omsOrder.getStatus()== OrderStatusEnum.NON_PAY.getOrderStatus()){
                omsOrder.setStatus(OrderStatusEnum.CLOSED.getOrderStatus());
                omsOrderService.updateById(omsOrder);
            }
            channel.basicAck(tag,false);
        } catch (Exception e) {
            try {
                log.error("从order.release.queue队列中获得订单信息，处理失败:{}",omsOrder.getOrderSn());
                //Thread.sleep(1000);
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                log.error("处理失败的信息回到消息队列的操作失败:{}",omsOrder.getOrderSn());
            }
        }
    }
}
